<template>
	<scroll-view class="message-list-container" scroll-y="true" :scroll-into-view="scrollView" :refresher-enabled="true"
		@refresherrefresh="refresh" :scroll-top="scrollTop" :refresher-triggered="triggered">
		<view id="message-scroll" style="width: 100%">
			<view style="height: 500rpx;"></view>
			<view class="no-message" v-if="isCompleted">没有更多啦</view>
<!-- 			<view class="flex_r fa_c info">
				<view class="info-img">
					
				</view>
				<view class="info-srt">
					
				</view>
				<view class="flex1 text-tex">
					文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案
				</view>
			</view> -->
			<view class=""> 
				<view v-for="item in messageList" :key="item.ID" class="t-message">
					<view v-if="conversation.type !== '@TIM#SYSTEM'" :id="item.ID">
						<view class="t-message-item">
							<TUI-TipMessage v-if="item.type === 'TIMGroupTipElem'" :message="item"></TUI-TipMessage>
							<view v-if="item.type !== 'TIMGroupTipElem'"
								:class="item.flow === 'out' ? 't-self-message' : 't-recieve-message'">
								<image class="t-message-avatar" v-if="item.flow === 'in'"
									:src="item.avatar || 'https://jw-uniapp.oss-cn-beijing.aliyuncs.com/static/images/avatar.png'"
									@click="goUser(item.ID, item.avatar, item.nick)"></image>
								<view class="read-receipts" v-if="conversation.type === 'C2C' && item.flow === 'out'">
									<view v-if="item.isPeerRead">已读</view>
									<view v-else>未读</view>
								</view>
								<view @longpress="longpress(item)">
									<TUI-TextMessage v-if="item.type === 'TIMTextElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-TextMessage>
									<TUI-ImageMessage v-if="item.type === 'TIMImageElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-ImageMessage>
									<TUI-VideoMessage v-if="item.type === 'TIMVideoFileElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-VideoMessage>
									<TUI-AudioMessage v-if="item.type === 'TIMSoundElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-AudioMessage>
									<TUI-CustomMessage v-if="item.type === 'TIMCustomElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-CustomMessage>
									<TUI-FaceMessage v-if="item.type === 'TIMFaceElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-FaceMessage>
									<TUI-FileMessage v-if="item.type === 'TIMFileElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-FileMessage>
								</view>
								<image class="t-message-avatar" v-if="item.flow === 'out'"
									:src="item.avatar || 'https://jw-uniapp.oss-cn-beijing.aliyuncs.com/static/images/avatar.png'"
									@click="goUser(userID, avatar, '我')"></image>
							</view>
						</view>
					</view>
					<view v-else :id="item.ID" :data-value="item.ID">
						<TUI-SystemMessage :message="item"></TUI-SystemMessage>
					</view>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import TUITextMessage from '../message-elements/text-message/index';
	import TUIImageMessage from '../message-elements/image-message/index';
	import TUIVideoMessage from '../message-elements/video-message/index';
	import TUIAudioMessage from '../message-elements/audio-message/index';
	import TUICustomMessage from '../message-elements/custom-message/index';
	import TUITipMessage from '../message-elements/tip-message/index';
	import TUISystemMessage from '../message-elements/system-message/index';
	import TUIFaceMessage from '../message-elements/face-message/index';
	import TUIFileMessage from '../message-elements/file-message/index';

	export default {
		data() {
			return {
				avatar: '',
				userID: '',
				// 当前会话
				messageList: [],
				// 自己的 ID 用于区分历史消息中，哪部分是自己发出的
				scrollView: '',
				scrollTop: 0,
				triggered: true,
				nextReqMessageID: '',
				// 下一条消息标志
				isCompleted: false, // 当前会话消息是否已经请求完毕
			};
		},

		components: {
			TUITextMessage,
			TUIImageMessage,
			TUIVideoMessage,
			TUIAudioMessage,
			TUICustomMessage,
			TUITipMessage,
			TUISystemMessage,
			TUIFaceMessage,
			TUIFileMessage,
		},
		props: {
			conversation: {
				type: Object,
				default: () => {},
			},
		},
		watch: {
			conversation: {
				handler: function(newVal) {
					if (!newVal.conversationID) return;
					this.setData({
							conversation: newVal,
						},
						() => {
							this.getMessageList(newVal);
						}
					);
				},
				immediate: true,
				deep: true,
			}
		},
		mounted() {
			uni.$TUIKit.getMyProfile().then(res => {
				this.avatar = res.data.avatar;
				this.userID = res.data.userID;
			});
			uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived, this);
			uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this);
			this.scrollToButtom();
		},

		destroyed() {
			// 一定要解除相关的事件绑定
			uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived);
		},
		methods: {
			goUser(id, avatar, nick) {
				uni.navigateTo({
					url: '/im/information/information?index=2&id=' + id + '&url=' + avatar + '&nick=' + nick,
				});
			},
			// 撤回消息
			revokeMessage(item) {
				uni.$TUIKit
					.revokeMessage(item)
					.then(imResponse => {
						this.updateMessageByID(imResponse.data.message.ID);

						// 消息撤回成功
					})
					.catch(imError => {
						wx.showToast({
								title: '超过2分钟消息不支持撤回',
								duration: 800,
								icon: 'none',
							}),
							// 消息撤回失败
							console.warn('revokeMessage error:', imError);
					});
			},
			// 删除消息
			deleteMessage(item) {
				uni.$TUIKit
					.deleteMessage([item])
					.then(imResponse => {
						this.updateMessageByID(imResponse.data.messageList[0].ID);
						wx.showToast({
							title: '删除成功!',
							duration: 800,
							icon: 'none',
						});
					})
					.catch(() => {
						wx.showToast({
							title: '删除失败!',
							duration: 800,
							icon: 'error',
						});
					});
			},
			// 更新messagelist
			updateMessageByID(deleteMessageID) {
				const {
					messageList
				} = this.messageList;
				const deleteMessageArr = messageList.filter(item => item.ID === deleteMessageID);
				this.messageList = deleteMessageArr;
				this.setMessageList()
			},
			longpress(item) {
				uni.showActionSheet({
					itemList: ['撤回', '删除'],
					success: res => {
						if (res.tapIndex + 1 == 1) {
							this.revokeMessage(item);
						}
						if (res.tapIndex + 1 == 2) {
							this.deleteMessage(item);
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					},
				});
			},
			refresh() {
				if (this.isCompleted) {
					this.setData({
						isCompleted: true,
						triggered: false,
					});
					return;
				}
				this.getMessageList(this.conversation);
				setTimeout(() => {
					this.setData({
						triggered: false,
					});
				}, 2000);
			},

			getMessageList(conversation) {
				if (!this.isCompleted) {
					uni.$TUIKit
						.getMessageList({
							conversationID: conversation.conversationID,
							nextReqMessageID: this.nextReqMessageID,
							count: 15,
						})
						.then(res => {
							const {
								messageList
							} = res.data; // 消息列表。
							this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
							this.isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
							this.messageList = [...messageList, ...this.messageList];
							this.setMessageList();
							this.$handleMessageRender(this.messageList, messageList);
						});
				}
			},
			setMessageList(){
				// for(let i in this.messageList){
					// let item = this.messageList[i];
					// this.messageList[i].callingmessage = JSON.parse(item.payload.data)
					// console.log(this.messageList[i].callingmessage)
				// }
				this.scrollToButtom();
			},

			// 自己的消息上屏
			updateMessageList(msg) {
				this.messageList = [...this.messageList, msg];
				this.setMessageList();
				this.scrollToButtom();
			},

			// 消息已读更新
			$onMessageReadByPeer() {
				this.setData({
					messageList: this.messageList,
				});
			},
			scrollToButtom() {
				const query = uni.createSelectorQuery().in(this);
				let nodesRef = query.select('#message-scroll');
				nodesRef
					.boundingClientRect(res => {
						this.$nextTick(() => {
							//进入页面滚动到底部
							this.scrollTop = res.height;
						});
					})
					.exec();
			},
			// 收到的消息
			$onMessageReceived(value) {
				// 若需修改消息，需将内存的消息复制一份，不能直接更改消息，防止修复内存消息，导致其他消息监听处发生消息错误
				const event = value;
				const list = [];
				event.data.forEach(item => {
					if (item.conversationID === this.conversation.conversationID) {
						list.push(Object.assign(item));
					}
				});
				this.messageList = this.messageList.concat(list);
				this.setMessageList()
				this.scrollToButtom();
			},

			// 历史消息渲染
			$handleMessageRender(messageList) {
				if (messageList.length > 0) {
					this.setData({
							messageList,
						},
						() => {}
					);
					this.$nextTick(() => {
						//进入页面滚动到底部
						this.scrollTop = 9999;
					});
				}
			},
		},
	};
</script>
<style lang="scss">
	@import './index.css';
	.info{
		box-sizing: border-box;
		padding: 20rpx;
		width: 500rpx;
		height: 200rpx;
		margin: 0 auto 20rpx auto;
		border-radius: 20rpx;
		background-color: #ececec;
		.info-img{
			width: 60rpx;
			height: 60rpx;
			background-color: #d5d5d5;
		}
		.info-srt{
			width: 1px;
			height: 100rpx;
			margin: 0 20rpx;
			background-color: #c6c6c6;
		}
		.text-tex{
			
		}
	}

</style>